import { db } from "@/api";
import { ConfirmUtil, ResultUtil } from "@/util";
import { useStore } from "@/util/hooks";
import { Dropdown, Menu } from "@arco-design/web-react";
import { Delete, Edit } from "@icon-park/react";
import { DBTableAtom } from ".";
import { DBTableModalAtom } from "./modal";

const iconStyle = {
  marginRight: 8,
  fontSize: 16,
  transform: "translateY(1px)",
};

export const ContextMenuRow = (props: any) => {
  const dbTableStore = useStore(DBTableAtom);
  const dbTableModalStore = useStore(DBTableModalAtom);
  const { record } = props;

  function onEditClick() {
    dbTableModalStore.updateStore({
      open: true,
      type: "update",
      record: record,
    });
  }

  async function onRemoveClick() {
    const res = await db.deleteDB(record.id);
    if (ResultUtil.showError(res)) {
      const listRes = await db.list();
      dbTableStore.updateStore({
        selected: undefined,
        data: listRes.data,
      });
    }
  }

  return (
    <Dropdown
      trigger="contextMenu"
      position="bl"
      droplist={
        <Menu>
          <Menu.Item key="edit" onClick={onEditClick}>
            <Edit style={iconStyle} />
            编辑
          </Menu.Item>
          <Menu.Item
            key="delete"
            onClick={() => {
              ConfirmUtil.removeConfirm(onRemoveClick);
            }}
          >
            <Delete style={iconStyle} />
            删除
          </Menu.Item>
        </Menu>
      }
    >
      <tr {...props} />
    </Dropdown>
  );
};
